<script setup>
import { nextTick, provide, ref } from 'vue'
import { useDark, useToggle } from '@vueuse/core'
import router from '@renderer/router'
import { appInit, settingMenuList } from '@renderer/common/app'

import AppTable from '@renderer/components/app-tabbar/app-tabbar'
import AppMenu from '@renderer/components/app-menu/app-menu'

const routes = [...router.getRoutes()] // 获取路由列表
const menu = routes.filter((item) => !item.meta.hidden)
const titleName = ref(import.meta.env.VITE_NAME)
const currMenu = ref(menu[0].name)
const loading = ref(false)
const currRoute = ref(router.currentRoute.value)
const tabbarName = ref(menu.map((item) => item.name))
const appScrollbar = ref(null)

appInit()
// 通过 provide 提供一个 titleName 的值
provide('titleName', (title) => (titleName.value = title))
provide('loading', (isLoad) => {
  loading.value = isLoad
})

// 设置主题
useDark({
  onChanged(dark) {
    app?.useDark?.(dark)
  }
})
const isDark = useDark()
useToggle(isDark)

// 路由前置守卫
router.beforeEach(async (to, from, next) => {
  loading.value = true
  next()
})

// 路由后置守卫
router.afterEach((to) => {
  loading.value = false
  currRoute.value = to
  if (to?.meta?.title && to.name !== 'Index') {
    titleName.value = to.meta.title
  } else {
    titleName.value = import.meta.env.VITE_NAME
  }
  nextTick(() => {
    appScrollbar.value?.update()
  })
})
</script>

<template>
  <div id="main" v-loading="loading" class="flex flex-col h-full w-full">
    <!-- 标题栏 -->
    <div class="titlebar overflow-hidden">
      <span class="truncate inline-block">{{ titleName }}</span>
    </div>
    <!-- 视图 -->
    <div class="flex flex-row h-full justify-between overflow-hidden">
      <AppTable v-show="tabbarName.includes(currRoute.name)" v-model="currMenu">
        <AppMenu v-model="settingMenuList"></AppMenu>
      </AppTable>
      <!-- 内容区域 -->
      <div class="main-box">
        <el-scrollbar ref="appScrollbar" class="h-full">
          <router-view v-slot="{ Component }">
            <keep-alive :include="tabbarName">
              <component :is="Component"></component>
            </keep-alive>
          </router-view>
        </el-scrollbar>
      </div>
    </div>
  </div>
</template>

<style scoped></style>
